Ext.define('App.view.BaseProcessWindow', {
    extend: "App.view.common.Window",
    alias: 'widget.BaseProcessWindow',
    processDefinitionKey:'',
    isProcessOn:false,//审批流程是否被提交的开关，true时，提交业务成功之后会提交流程
    clickYWSubmit:false,//是否点击了该窗体的提交按钮
    floatBtnDownNames:[//浮动按钮配置
        {title:'基本信息',downName:'commonFieldSet[name=subject]'},
        {title:'审批流程',downName:'approvalMain'}
    ],
    buttons: [
        'close'
    ],
    submitProcessNode:[],//配置那些节点需要提交业务
    processItemControlConfig:[//流程节点控制页面是否显示、只读、可编辑配置
        /*{
         index: 0,//当前对象的items数组索引
         read:['-']//所有节点
         },
         {
         index: 1,
         read:['4','7-'],//4或者大于等于7的节点
         edit:['4']//周期变更类型选择：校准/验证周期缩短时,在仪校担当节点（N3）出现且必填
         },
         //符号 '-'说明：
         '-'单独出现表示所有节点
         '1-'表示大于等于1的所有节点
         '1-6'表示大于等于1且小于等于6的节点
         '-6'表示小于等于6的所有节点
         */
    ],
    initComponent: function () {
        var me = this;
        me.items = Ext.clone(me.items);
        me.processItemControl();
        //如果当前编辑页面判断为不需要提交业务数据或者不是当前处理人，将页面状态改为只读状态
        if(!me.getIsProcessOn() && me.actionType == 'edit'){
            me._isView = true;
        }
        //判断是否是当前处理人，如果是当前处理人，界面可编辑，否则不可编辑
        if(me.actionType == 'edit' && !me.isCurHandlers()){
            me._isView = true;
        }

        //添加流程页面
        me.addProcessPage();

        me.callParent();

        me.hideSubmitBtn();
        me.hideTempSaveBtn();
    },
    doReadOnlyItem:function (i) {
        this.items[i].hidden = false;
        this.items[i].items[0].disabled = false;
        this.items[i].items[0].readOnly = true;
    },
    doEditOnlyItem:function (i) {
        this.items[i].items[0].readOnly = false;
    },
    processItemControl:function () {
        var itemControls = this.processItemControlConfig;
        if(!itemControls || !this._record){
            return;
        }
        var i,editFlag, readFlag, processNode;

        //驳回到起草节点时，不进行item控制保持草稿状态
        if(this._record.curNodesId == 'startTask'){
            return;
        }
        if(this._record.processStatus == '4'){//流程结束所有配置页面可见可读
            for (i = 0; i < itemControls.length; i++) {
                this.doReadOnlyItem(itemControls[i].index);
            }
        }else if (this._record.curNodesId) {
            processNode = this._record.curNodesId;

            for (i = 0; i < itemControls.length; i++) {
                readFlag = this.checkIsControl(itemControls[i].read,processNode);
                //结束节点默认都可见且是只读状态
                if(readFlag){
                    this.doReadOnlyItem(itemControls[i].index);
                }
                editFlag = this.checkIsControl(itemControls[i].edit,processNode);
                if(editFlag){
                    this.doEditOnlyItem(itemControls[i].index);
                }
            }
        }
    },

    /**
     * 检查当前节点是否在流程节点控制页面配置中
     * @param readArr 节点配置数组
     * @param processNum 流程节点序号
     * @param processNodeId 流程节点id
     * @returns {boolean}
     */
    checkIsControl:function (readArr,processNodeId) {
        if(!readArr || !processNodeId){
            return false;
        }
        var processNodeIdArr = processNodeId.split(",");
        for(var i=0; i<processNodeIdArr.length; i++){
             if(this.checkIsControlSub(readArr,processNodeIdArr[i])){
                 return true;
             }
        }
        return false;
    },

    checkIsControlSub: function (readArr,processNodeId) {
        var j, str, temps;
        //除去首字符N，获取流程节点的序号
        var processNum = processNodeId.substr(1);
        for(j=0; j<readArr.length; j++){
            str = readArr[j];
            //如果配置的字符串等于流程节点id
            if(str === processNodeId){
                return true;
            }
            processNum = Number(processNum);
            if(str.indexOf('-') > -1){//如果字符串中存在符号 '-'
                if(str.length === 1){//单独存在符号'-'，表示支持所有流程节点
                    return true;
                }else if(str.substr(0,1) === '-'){//'-5'符号'-'在首位，表示节点序号小于5的所有节点
                    if(processNum <= str.substr(1)){
                        return true;
                    }
                }else if(str.substr(str.length-1,1) === '-'){//'5-'符号'-'在末尾，表示节点序号大于5的所有节点
                    if(processNum >= str.substr(0,str.length - 1)){
                        return true;
                    }
                }else{//符号'5-10'在中间，表示节点序号大于等于5且小于等于10的节点
                    temps = str.split('-');
                    if(processNum >= temps[0] && processNum <= temps[1]){
                        return true;
                    }
                }
            }else {
                if(processNum == str){
                    return true;
                }
            }
        }
        return false;
    },

    hideSubmitBtn:function () {
        //如果存在流程状态，隐藏提交按钮（当前用户是办理人时，才显示提交按钮）
        if(this._record && this._record.processStatus != '0'){
            var submit = this.down('button[name=submit]');
            if(submit){
                submit.hide();
                submit.disable();
            }
        }
    },
    hideTempSaveBtn:function () {
        //如果流程状态不是草稿状态，隐藏暂存按钮
        if(this._record && this._record.processStatus && this._record.processStatus != '0'){
            var tempSave = this.down('button[name=tempSave]');
            if(tempSave){
                tempSave.hide();
                tempSave.disable();
            }
        }
    },
    /**
     * 当前用户是办理人显示提交按钮
     * @param callBack
     */
    isAssigneeShowSubmitBtn:function (callBack) {
        /*if(callBack.isAssignee){
            var btn = this.down('button[name=submit]');
            if(btn){
                btn.enable();
                btn.show();
            }
        }*/
    },
    //添加流程页面
    addProcessPage: function () {
        var win = this,
            processDefinitionKey = this.processDefinitionKey,
            view = this._isView,
            items = this.items
        ;

        var baseParams = {
            processDefinitionKey: processDefinitionKey,
            token:App.Application.token
        };
        if(this._record){
            baseParams.businessKey = this._record.id;
        }
        if (this._record && this._record.processInstanceId) {
            baseParams.processInstanceId = this._record.processInstanceId;
            delete baseParams.processDefinitionKey;
        }
        //如果是编辑窗口，流程页面强制置为非只读状态
        if (this.actionType == 'edit') {
            view = false;
        }

        //添加流程审批页面到业务表单下方
        items.push({
            margin: '5 0 40 0',
            xtype: 'approvalMain',
            triggerObj: this,
            //startSubmitHidden: true,
            isProcessView: view,//流程是否设置为查看状态，查看状态将移除操作区域
            baseParams: baseParams,
            //获取初始化数据成功，进行必要的逻辑处理
            initSuccess: function(callBack){
                //当前用户是办理人显示提交按钮
                win.isAssigneeShowSubmitBtn(callBack);
            },
            //接口：拦截提交按钮的提交动作，并执行业务端数据提交，提交成功之后，执行审批流程提交
            submitBefore: function (btn) {
                var process = this;
                var approvalMain = win.down('approvalMain');
                var param = process.getValues();
                if(param.cz != '101' && param.cz != '1' && param.cz != '112'){//如果不是选择通过、提交文档操作，直接走提交流程的方法
                    process._submit();
                    return;
                }
                if(!win.processSubmitBefore(this,approvalMain,param)){
                    return;
                }
                if (!win.clickYWSubmit && win.getIsProcessOn()) {
                    var submitBtn = win.down('button[name=submit]');
                    win.process = process;
                    //提交业务数据
                    win._submit(submitBtn);
                } else {
                    setTimeout(function () {
                        process._submit();
                    },500);
                }

            },
            submitSuccess: function (callBack) {
                if (win._targetObject) {//刷新列表
                    win._targetObject._refresh();
                }
                //刷新待办
                var gtask = Ext.getCmp('main-gtasksgrid');
                if (gtask) {
                    gtask.getStore().load();
                }
                win.processSubmitSuccess(callBack);
                win.close();
            },
            //接口：审批流程提交失败回调方法
            submitFailure: function (callBack) {
                App.ux.Toast.show('提示', "流程发起失败！",'e');
            }
        });

        //添加浮动按钮
        var floatWindow = Ext.create({
            xtype: 'commonFloatWindow',
            scrollMain: this,
            buttonItems: win._getButtonItems()
        });

        //将浮动按钮展示到窗口的下方靠左200个像素的位置
        win.on({
            boxready: function () {
                this.add(floatWindow);
                floatWindow._showAt(this.width, this.height);
            },
            afterlayout: function () {
                floatWindow._showAt(this.width, this.height);
            }
        });

        this.items = items;
    },
    _getButtonItems:function () {
        var items = [];
        var i;
        for(i=0 ; i<this.floatBtnDownNames.length; i++){
            items.push({xtype: 'panel', title: this.floatBtnDownNames[i].title, downName: this.floatBtnDownNames[i].downName});
        }
        return items;
    },
    _submit: function(btn,form){
        form = this.down('form');
        if(btn.name === 'submit'){
            this.isProcessOn = this.getIsProcessOn();
            //当在流程页面中选择通过、提交文档操作，不需要提交业务数据
            if(this.down('approvalProcess')){
                var param = this.down('approvalProcess').getValues();
                if(param.cz != '101' && param.cz != '1' && param.cz != '112'){
                    this.isProcessOn = false;
                }
            }
            if(!this.isProcessOn){
                var approvalMain = this.down('approvalMain');
                if(approvalMain){
                    approvalMain.submit();//发起流程
                }
                return;
            }
        }
        this.callParent([btn,form]);
    },
    //获取提交流程时，是否提交业务的状态
    getIsProcessOn:function () {
        //新增时发起流程
        if(!this._record){
            return true;
        }
        //草稿状态时发起流程
        if(!this._record.processStatus || this._record.processStatus === '0'){
            return true;
        }
        //起草节点
        if(this._record.curNodesId === 'startTask'){
            return true;
        }
        if(this.checkIsControl(this.getSubmitProcessNode(),this._record.curNodesId)){
            return true;
        }
        return false;
    },
    getSubmitProcessNode:function () {
        if(this.submitProcessNode.length > 0){
            return this.submitProcessNode;
        }
        var con = this.processItemControlConfig;
        var submitProcessNode = [];
        for(var i=0 ; i<con.length; i++){
            if(con[i].edit){
                submitProcessNode = Ext.Array.merge(submitProcessNode,con[i].edit);
            }
        }
        return submitProcessNode;
    },
    /**
     * 重写父类的方法，当业务提交成功之后，在提交流程
     * @param btn
     * @param response
     * @param options
     * @private
     */
    _submitSuccess: function (btn, response, options) {
        btn.disable();
        //提交流程
        if (this.isProcessOn && 'submit' == btn.name) {//业务数据保存成功，执行审批流程提交
            var approvalMain = this.down('approvalMain');
            if(response.data){
                if(Ext.isString(response.data)){
                    approvalMain.baseParams.businessKey = response.data;
                }
                if(response.data.id){
                    approvalMain.baseParams.businessKey = response.data.id;
                }
                if(response.data.variables){
                    Ext.apply(approvalMain.customParams, response.data.variables);
                }
                if(response.data.processInstanceName){
                    Ext.apply(approvalMain.customParams, {todoTitle:response.data.processInstanceName});
                }
            }

            if(this.process){//存在：表示点击了流程页面的提交按钮
                this.process._submit();//发起流程
                this.process = null;
            }else{//点击窗口的提交按钮
                this.clickYWSubmit = true;//点击当前窗体提交按钮标记
                approvalMain.submit();//发起流程
                this.clickYWSubmit = false;
            }
            this.isProcessOn = false;//关闭业务提交开关
        }else{
            if(btn){
                if(this.autoPrompt){
                    App.ux.Toast.show('提示',btn.text + '成功！','s');
                }
            }
            if(this._targetObject){
                this._targetObject._refresh();
            }
            this.close();
        }
    },

    /**
     * 判断是不是当前处理人，是返回true,否则返回false
     * @returns {boolean}
     */
    isCurHandlers: function () {
        if(this._record && !this._record.curHandlerAccs){
            return true;
        }
        var curHandlers = false;
        if(this._record && this._record.curHandlerAccs){
            var curHandlerAccs = this._record.curHandlerAccs.split(",");
            var curAcc = Ext.CSOTUserInfo.userId;
            if(curHandlerAccs.indexOf(curAcc) != -1){
                curHandlers = true;
            }
        }
        return curHandlers;
    },
    reviewData:function(url){
        var me = this,params = {
            id: me._record.id
        };
        App.ux.Ajax.request({
            url: url,
            method: 'post',
            params: params,
            success: function (response) {
                Ext.suspendLayouts();
                me._addValuesToComponent(response.data);
                Ext.resumeLayouts(true);
            },
            failure: function (response) {
            }
        });
    },

    /**
     * 重写校验方法
     * @returns {*}
     */
    isValid: function(){
        var valid = this.callParent(arguments);
        //如果是暂存，至少必填主题
        var docSubject = this.down('[name=docSubject]');
        if(!this.openValidation && !docSubject.validate()){
            if(valid.valid){
                var message = "当前表单";
                valid.valid = false;
                valid.message = message + ' ['+docSubject.config.fieldLabel+']'+'合法性验证失败！';
            }
        }
        return valid;
    },

    /**
     * 流程引擎提交成功后的处理逻辑
     * @param callback
     */
    processSubmitSuccess:function (callback) {

    },
    /**
     * 流程引擎提交前的动作
     * @param callback
     * return true 如果返回false将中断流程提交
     */
    processSubmitBefore:function (process,approvalMain,param) {
        return true;
    }
});